package fastServer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Header;
import protocol.IOMessage;
import protocol.MessageType;

/**
 * 与客户端同步信息num
 * @author root
 * @time 7:14:09 PM Sep 29, 2016
 */
public class MesSyncServerHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelActive(ctx);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
	    IOMessage message = (IOMessage)msg;
		if(message.getHeader() != null && message.getHeader().getType()
				                       == MessageType.ALL_RESP.value()){
			System.out.println("server receive \"ALL_RESP\" from client -- " + message);
		}else{
			if(message.getHeader() != null && message.getHeader().getType()
					                       == MessageType.CHAT_REQ.value()){
				
				System.out.println("receive MES from client -- " + message);
				
				JSONObject chatJson = JSON.parseObject(message.getBody());
				String from = chatJson.getString("from");
				String to = chatJson.getString("to");
				String content = chatJson.getString("content");
				
				ChannelHandlerContext toCtx = LoginAuthRespHandler.userNode.get(to);
				if(toCtx != null){
					
					IOMessage message_to = new IOMessage();
					Header header = new Header();
					header.setType(MessageType.CHAT_RESP.value());
					message_to.setHeader(header);
					
					JSONObject mesToJson = new JSONObject();
					mesToJson.put("from", from);
					mesToJson.put("to", to);
					mesToJson.put("content", content);
					mesToJson.put("num", 1);
					message_to.setBody(mesToJson.toJSONString());
					
					toCtx.writeAndFlush(message_to);
				}
			}else{
				if(message.getHeader() != null && message.getHeader().getType()
	                       == MessageType.CHAT_SYNC.value()){
					System.out.println("** -- CHAT_SYC -- ** " + message);
				}
				ctx.fireChannelRead(msg);
			}
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		//super.exceptionCaught(ctx, cause);
	}
}
